# -*- coding: utf-8 -*-
from django.shortcuts import render, get_object_or_404, render_to_response
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.views import generic
from django.utils import timezone
from django.core import serializers
from .models import Village, Deadman
from lunardate import LunarDate
import redis, sys, json, re
import datetime

reload(sys)
sys.setdefaultencoding('utf8')


@login_required(login_url="/login/")
def index_view(request, village='all'):
    template_name = 'index.html'

    village = request.GET.get("village")
    if not village:
        village = 'all'
    deaddate = request.GET.get("deaddate")
    if not deaddate:
        deaddate = 'all'
    page = request.GET.get('page')

    deadman_all = []
    if village and village != 'all':
        village_obj = Village.objects.filter(name=village).first()
        deadman_all = Deadman.objects.filter(village=village_obj).order_by('dead_date')
    else:
        deadman_all = Deadman.objects.all().order_by('dead_date')

    deadman_list = []
    prog = re.compile(".*_d$")
    for deadman_obj in deadman_all:
        list_result = False
        if deaddate != 'all':
            try:
                deadman_date_map = deadman_obj.GetSacrificeDay()
                deadman_day_list = [ld for ld in deadman_date_map.keys() if prog.search(ld)]
                for sf_day in deadman_day_list:
                    #print deadman_date_map[sf_day].strftime("%Y-%m-%d"), deaddate
                    if deadman_date_map[sf_day].strftime("%Y-%m-%d") == deaddate:
                        list_result = True
                        #print '==================='
            except Exception as e:
                pass
        else:
            list_result = True
        if list_result:
            deadman_map = {}
            deadman_map['deadman'] = deadman_obj
            deadman_map['sf_day'] = deadman_obj.GetSacrificeDay()
            deadman_list.append(deadman_map)

    paginator = Paginator(deadman_list, 10) # Show 10 contacts per page
    try:
        deadman_page = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        deadman_page = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        deadman_page = paginator.page(paginator.num_pages)

    return render_to_response(template_name, locals(), context_instance=RequestContext(request))

@login_required(login_url="/login/")
def get_village_list(request):
    village_list = []
    village_all = Village.objects.all().order_by('name')
    for village in village_all:
        village_list.append(village.name)
    return HttpResponse(json.dumps(village_list, ensure_ascii=False), content_type='application/javascript')
